from queue import Queue

import yaml
from tools.log import logger
from tools.lock.file_lock import FileLock
from PIL import Image

notify_buffer = Queue(maxsize=30)

def write_meta(file,meta_yaml):
    with open(file,"w",encoding='utf-8') as wd:
        yaml.safe_dump(meta_yaml,wd)    

def work(global_conf,camera_conf):
    pending_file = global_conf['share']['pending']['file']  
    pending_lock = global_conf['share']['pending']['lock']
    env = global_conf['environment']
    loc =   FileLock(env+pending_lock)
    fil = env+pending_file

    while True:
        frame,meta = notify_buffer.get()
        Image.fromarray(frame).save(meta["dir"]+meta["image"]) #RGB
        logger.info("保存图片:"+meta["dir"]+meta["image"])
        meta["only_image"]=True
        write_meta(meta["dir"] +"meta.yaml",meta)  
        logger.info(f'完成元数据{meta["dir"] +"meta.yaml"}')
        with loc:
            with open(fil,"a",encoding="utf-8") as file:
                file.write(meta["dir"]+"\n")
        logger.info(f"{meta['id']} 通知完毕")